const mysql = require('mysql2/promise');

/**
 * 调试特定的外键约束问题
 */
async function debugForeignKey() {
  console.log('🔍 调试外键约束 FK_934ec047f4bbc3f527df0db7fdb...');
  
  const connection = await mysql.createConnection({
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs',
    timezone: '+08:00'
  });

  try {
    // 1. 检查这个约束是否存在于数据库中
    const [constraints] = await connection.execute(`
      SELECT 
        CONSTRAINT_NAME,
        TABLE_NAME,
        COLUMN_NAME,
        REFERENCED_TABLE_NAME,
        REFERENCED_COLUMN_NAME
      FROM 
        INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
      WHERE 
        REFERENCED_TABLE_SCHEMA = 'nextjs' 
        AND CONSTRAINT_NAME = 'FK_934ec047f4bbc3f527df0db7fdb'
    `);
    
    console.log(`📋 找到 ${constraints.length} 个名为 FK_934ec047f4bbc3f527df0db7fdb 的约束:`);
    constraints.forEach((constraint, index) => {
      console.log(`   ${index + 1}. 表: ${constraint.TABLE_NAME}, 列: ${constraint.COLUMN_NAME} -> ${constraint.REFERENCED_TABLE_NAME}.${constraint.REFERENCED_COLUMN_NAME}`);
    });
    
    // 2. 检查所有外键约束
    const [allConstraints] = await connection.execute(`
      SELECT 
        CONSTRAINT_NAME,
        TABLE_NAME,
        COLUMN_NAME,
        REFERENCED_TABLE_NAME,
        REFERENCED_COLUMN_NAME
      FROM 
        INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
      WHERE 
        REFERENCED_TABLE_SCHEMA = 'nextjs' 
        AND REFERENCED_TABLE_NAME IS NOT NULL
      ORDER BY CONSTRAINT_NAME
    `);
    
    console.log(`\n📋 数据库中总共有 ${allConstraints.length} 个外键约束:`);
    allConstraints.forEach((constraint, index) => {
      console.log(`   ${index + 1}. ${constraint.CONSTRAINT_NAME}: ${constraint.TABLE_NAME}.${constraint.COLUMN_NAME} -> ${constraint.REFERENCED_TABLE_NAME}.${constraint.REFERENCED_COLUMN_NAME}`);
    });
    
    // 3. 检查表是否存在
    const [tables] = await connection.execute(`
      SELECT TABLE_NAME 
      FROM INFORMATION_SCHEMA.TABLES 
      WHERE TABLE_SCHEMA = 'nextjs'
      ORDER BY TABLE_NAME
    `);
    
    console.log(`\n📋 数据库中总共有 ${tables.length} 个表:`);
    tables.forEach((table, index) => {
      console.log(`   ${index + 1}. ${table.TABLE_NAME}`);
    });
    
    // 4. 尝试手动删除这个约束（如果存在）
    if (constraints.length > 0) {
      console.log('\n🧹 尝试删除重复的约束...');
      for (const constraint of constraints) {
        try {
          await connection.execute(`ALTER TABLE \`${constraint.TABLE_NAME}\` DROP FOREIGN KEY \`${constraint.CONSTRAINT_NAME}\``);
          console.log(`✅ 已删除约束: ${constraint.CONSTRAINT_NAME} (表: ${constraint.TABLE_NAME})`);
        } catch (error) {
          console.log(`⚠️ 删除约束失败: ${constraint.CONSTRAINT_NAME} - ${error.message}`);
        }
      }
    }
    
  } catch (error) {
    console.error('❌ 调试外键约束失败:', error.message);
    throw error;
  } finally {
    await connection.end();
  }
}

// 执行调试
debugForeignKey()
  .then(() => {
    console.log('✅ 外键约束调试完成');
    process.exit(0);
  })
  .catch((error) => {
    console.error('💥 外键约束调试失败:', error.message);
    process.exit(1);
  });
